package com.anbinh.doctor.fragment.account;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.anbinh.doctor.DetailtActivity;
import com.anbinh.doctor.R;
import com.anbinh.doctor.model.Address.Data.Item;
import com.anbinh.doctor.model.DataResponse;
import com.anbinh.doctor.model.ItemMeu;
import com.anbinh.doctor.model.UserLogin;
import com.anbinh.doctor.request.controller.ServerController;
import com.anbinh.doctor.service.request.OnRequest;
import com.anbinh.doctor.ui.GPSTracker;
import com.anbinh.doctor.ui.SlidingLayer;
import com.anbinh.doctor.utils.Utils;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.lsjwzh.widget.materialloadingprogressbar.CircleProgressBar;

public class FragmentAddLocation extends SherlockFragment {
	private static FragmentAddLocation fragment = null;
	private View mView;
	List<ItemMeu> mList;
	private FragmentActivity mFragmentActivity;
	private GoogleMap mMap;
	private LatLng location = null;
	private SlidingLayer mSlidingLayer;

	private EditText edPhongkhamName;
	private EditText edDiachi;
	private EditText edSodienthoai;
	private CheckBox rdCheckBox;
	private double latitude = 0;
	private double longitude = 0;
	private String clinic_name;
	private String mDiachi;
	private String mPhone;
	private UserLogin userLogin;
	private int is_default = 0;

	private CircleProgressBar loadding;
	public static int mKeyOption;

	public static FragmentAddLocation newInstance(int keyOption) {
		if (fragment == null) {
			fragment = new FragmentAddLocation();
		}
		mKeyOption = keyOption;

		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (activity instanceof FragmentActivity) {
			mFragmentActivity = (FragmentActivity) activity;
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}

	@Override
	public void onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu,
			com.actionbarsherlock.view.MenuInflater inflater) {
		menu.add(0, R.id.dia_diem_kham, Menu.NONE, "Hoàn thành")
				.setIcon(R.drawable.ic_done)
				.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (mKeyOption == Utils.UPDATE_LOCATION) {
			onUpData();
		} else {
			onAddData();
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onResume() {
		super.onResume();
		Utils.showMessage(getActivity(), "onresume");
		if (mKeyOption == Utils.UPDATE_LOCATION) {
			((DetailtActivity) getActivity()).setActionBarTitle(getResources()
					.getString(R.string.cap_nhat_dia_diem));
		} else {
			((DetailtActivity) getActivity()).setActionBarTitle(getResources()
					.getString(R.string.them_dia_diem));
		}

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment_add_location, null);
		return mView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mSlidingLayer = (SlidingLayer) mView.findViewById(R.id.slidingLayer);
		LayoutParams rlp = (LayoutParams) mSlidingLayer.getLayoutParams();
		mSlidingLayer.setStickTo(SlidingLayer.STICK_TO_BOTTOM);
		rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		rlp.width = LayoutParams.MATCH_PARENT;
		rlp.height = Utils.convertDpToPixel(245, getActivity());

		mSlidingLayer.setLayoutParams(rlp);
		mSlidingLayer.setShadowWidthRes(R.dimen.shadow);
		mSlidingLayer.setShadowDrawable(R.drawable.sidebar_shadow);

		loadding = (CircleProgressBar) mView.findViewById(R.id.loadding);

		edPhongkhamName = (EditText) mView.findViewById(R.id.edName);
		edDiachi = (EditText) mView.findViewById(R.id.edDiachi);
		edSodienthoai = (EditText) mView.findViewById(R.id.edSodienthoai);
		rdCheckBox = (CheckBox) mView.findViewById(R.id.rdDiadiem);
		rdCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (isChecked) {
					is_default = 1;
				} else {
					is_default = 0;
				}

			}
		});
		setDataView();
		mMap.addMarker(new MarkerOptions().position(location).icon(
				BitmapDescriptorFactory
						.fromResource(R.drawable.ic_location_map)));
		// Move the camera instantly to hamburg with a zoom of 15.
		mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 15));

		// Zoom in, animating the camera.
		mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);

		mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

			@Override
			public void onMapClick(LatLng point) {
				mMap.clear();
				MarkerOptions marker = new MarkerOptions().position(
						new LatLng(point.latitude, point.longitude)).icon(
						BitmapDescriptorFactory
								.fromResource(R.drawable.ic_location_map));
				LatLng position_input = new LatLng(point.latitude,
						point.longitude);
				mMap.addMarker(marker);
				mMap.moveCamera(CameraUpdateFactory.newLatLng(position_input));
				mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
				latitude = point.latitude;
				longitude = point.longitude;
				mSlidingLayer.openLayer(true);

			}
		});
		new CountDownTimer(500, 500) {

			@Override
			public void onTick(long millisUntilFinished) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onFinish() {
				mSlidingLayer.openLayer(true);
			}
		}.start();

	}

	public void setDataView() {
		if (mKeyOption == Utils.UPDATE_LOCATION) {
			Item item = FragmentListLocation.newInstance().getCurrentLocation();
			edDiachi.setText(item.getAddress());
			edPhongkhamName.setText(item.getClinic_name());
			edSodienthoai.setText(item.getPhone());
			String location[] = item.getMap_position().split(",");
			latitude = Double.parseDouble(location[0]);
			longitude = Double.parseDouble(location[1]);
			if (item.getIs_default() == 1) {
				rdCheckBox.setChecked(true);
			} else {
				rdCheckBox.setChecked(false);
			}
		} else {

			GPSTracker gps = new GPSTracker(getActivity());
			if (gps.canGetLocation()) {
				latitude = gps.getLatitude();
				longitude = gps.getLongitude();
			} else {
				gps.showSettingsAlert();
			}
			rdCheckBox.setChecked(false);
		}

		location = new LatLng(latitude, longitude);
		mMap = ((SupportMapFragment) mFragmentActivity
				.getSupportFragmentManager().findFragmentById(R.id.map))
				.getMap();

	}

	public void onClickItem(int position) {
		Bundle bundle = new Bundle();
		bundle.putInt(Utils.KEY, mList.get(position).getRegId());

		bundle.putString(Utils.TITLE, mList.get(position).getTitle());
		Utils.getNewIntent(getActivity(), bundle);

	}

	public boolean onValidateForm() {
		mSlidingLayer.openLayer(true);
		clinic_name = edPhongkhamName.getText().toString().trim();
		if (clinic_name.isEmpty()) {
			Utils.showMessage(getActivity(),
					getResources().getString(R.string.vui_long_nhap_ten));
			return false;
		}
		mDiachi = edDiachi.getText().toString().trim();
		if (mDiachi.isEmpty()) {
			Utils.showMessage(getActivity(),
					getResources().getString(R.string.vui_long_nhap_dia_chi));
			return false;
		}
		mPhone = edSodienthoai.getText().toString().trim();
		/*
		 * if (mPhone.isEmpty()) { Utils.showMessage( getActivity(),
		 * getResources().getString( R.string.vui_long_nhap_so_dien_thoai));
		 * return false; }
		 */

		if (!mPhone.isEmpty() && mPhone.length() > 11 || mPhone.length() < 10) {
			Utils.showMessage(
					getActivity(),
					getResources().getString(
							R.string.so_dien_thoai_khong_hop_le));
			return false;
		}
		userLogin = Utils.getAccountModel(getActivity(), Utils.KEY_USER);
		if (userLogin == null)
			return false;
		return true;
	}

	public void onAddData() {
		if (!onValidateForm())
			return;

		loadding.setVisibility(View.VISIBLE);
		ServerController.getInstance(getActivity()).reuquestAddressAdd(
				userLogin.getData().getToken(), clinic_name, mDiachi, 1,
				is_default, mPhone, latitude + "," + longitude,
				new OnRequest<DataResponse>() {

					@Override
					public void onSuccess(DataResponse data) {
						loadding.setVisibility(View.INVISIBLE);
						if (getActivity() == null)
							return;
						if (data.getResponsecode() >= 0) {
							Intent intent = new Intent();
							intent.putExtra(Utils.KEY, Utils.ADD_LOCATION);
							getActivity().setResult(Integer.MAX_VALUE, intent);
							getActivity().finish();
						}

						Utils.showMessage(getActivity(), data.getDescription());
					}

					@Override
					public void onError(int errorCode, String message) {
						loadding.setVisibility(View.INVISIBLE);
					}
				});

	}

	public void onUpData() {
		if (!onValidateForm())
			return;

		Item item = FragmentListLocation.newInstance().getCurrentLocation();
		loadding.setVisibility(View.VISIBLE);

		Log.d("onUpData", item.getIs_active() + "_" + item.getIs_default());

		ServerController.getInstance(getActivity()).reuquestAddressUpdate(
				userLogin.getData().getToken(), item.getId(), clinic_name,
				mDiachi, item.getIs_active(), is_default, mPhone,
				latitude + "," + longitude, new OnRequest<DataResponse>() {

					@Override
					public void onSuccess(DataResponse data) {
						loadding.setVisibility(View.INVISIBLE);
						if (data.getResponsecode() >= 0) {
							Intent intent = new Intent();
							intent.putExtra(Utils.KEY, Utils.ADD_LOCATION);
							getActivity().setResult(Integer.MAX_VALUE, intent);
							getActivity().finish();
						}

						Utils.showMessage(getActivity(), data.getDescription());
					}

					@Override
					public void onError(int errorCode, String message) {
						loadding.setVisibility(View.INVISIBLE);
					}
				});

	}

}
